package cn.jbolt.core.poi.word;

import cn.hutool.core.io.FileUtil;
import com.jfinal.kit.PathKit;

import java.io.File;
import java.util.Map;

/**
 * word数据封装
 *
 * @ClassName: JBoltWord
 * @author: JFinal学院-小木 QQ：909854136
 * @date: 2021年2月14日
 */
public class JBoltWord {
	/**
	 * 模板文件
	 */
	private File tplFile;
	/**
	 * 导出的文件名
	 */
	private String fileName;
	/**
	 * 模板数据
	 */
	private Map<String, Object> datas;

	private JBoltWord(File tplFile) {
		if (tplFile == null || FileUtil.exist(tplFile) == false) {
			throw new RuntimeException("File not exist:" + tplFile.getAbsolutePath());
		}
		this.tplFile = tplFile;
	}

	private JBoltWord(String tplPath) {
		if (FileUtil.isAbsolutePath(tplPath) == false) {
			tplPath = PathKit.getRootClassPath() + File.separator + "wordtpl" + File.separator + tplPath;
			if (FileUtil.exist(tplPath)) {
				this.tplFile = new File(tplPath);
			} else {
				throw new RuntimeException("File not exist:" + tplPath);
			}
		}

	}

	public static JBoltWord useTpl(String tplPath) {
		return createByTpl(tplPath);
	}

	public static JBoltWord useTpl(File tplFile) {
		return createByTpl(tplFile);
	}

	public static JBoltWord createByTpl(String tplPath) {
		if (tplPath.indexOf("wordtpl") == -1 && FileUtil.isAbsolutePath(tplPath) == false) {
			tplPath = "wordtpl" + File.separator + tplPath;
		}
		return createByTpl(FileUtil.file(tplPath));
	}

	public static JBoltWord createByTpl(File tplFile) {
		return new JBoltWord(tplFile);
	}

	public File getTplFile() {
		return tplFile;
	}

	public Map<String, Object> getDatas() {
		return datas;
	}

	public JBoltWord setDatas(Map<String, Object> datas) {
		this.datas = datas;
		return this;
	}

	public String getFileName() {
		return fileName;
	}

	public JBoltWord setFileName(String fileName) {
		this.fileName = fileName;
		return this;
	}

	/**
	 * 获取bytes
	 *
	 * @return
	 */
	public byte[] toByteArray() {
		return JBoltWordUtil.me.getWordBytes(this);
	}

	/**
	 * 存到文件
	 *
	 * @param saveFilePath
	 * @return
	 */
	public File toFile(String saveFilePath) {
		return JBoltWordUtil.me.saveFile(this, saveFilePath);
	}
}
